import {
	baseUrl
} from './config.js';

// 需要token的请求
function getToken() {
	return uni.getStorageSync('token');
}

// 轮播图列表 - 不需要token
export function cardlist() {
	return uni.request({
		url: `${baseUrl}/api/cards`,
		method: 'GET'
	});
}

// 题目分类-听力 - 不需要token
export function Categorylist_T() {
	return uni.request({
		url: `${baseUrl}/api/categories/search?keyword=`,
		method: 'GET'
	});
}

// 题目详情 - 需要token
export function listDetail(categoryId) {
  const token = getToken();
  if (!token) {
    return Promise.resolve([{ statusCode: 401, errMsg: '未登录' }, null]);
  }

  return new Promise((resolve) => {
    uni.request({
      url: `${baseUrl}/api/questions/by-category`,
      method: 'GET',
      data: {
        categoryId: categoryId
      },
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        // 处理响应
        if (res.statusCode === 200) {
          resolve([null, res]);
        } else {
          resolve([{ 
            statusCode: res.statusCode,
            errMsg: res.data?.message || '请求失败'
          }, null]);
        }
      },
      fail: (err) => {
        resolve([{
          statusCode: err.statusCode || 500,
          errMsg: err.errMsg || '网络错误'
        }, null]);
      }
    });
  });
}

// 登录接口
export function login02(account, password) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${baseUrl}/api/users/login`,
			method: 'POST',
			header: {
				'Content-Type': 'application/json'
			},
			data: {
				username: account,
				password: password
			},
			success: (res) => {
				resolve(res);
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
}


// 注册接口
export function register(username, password, email) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${baseUrl}/api/users/register`,
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      data: {
        username: username,
        password: password,
        email: email
      },
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data);
        } else {
          reject(new Error(res.data?.message || '注册失败'));
        }
      },
      fail: (err) => {
        reject(new Error(err.errMsg || '网络错误'));
      }
    });
  });
}